package com.example.ercmssystem2.controller;

import com.example.ercmssystem2.entity.Department;
import com.example.ercmssystem2.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/departments")
@CrossOrigin(origins = "*")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    // 创建部门
    @PostMapping
    public ResponseEntity<?> createDepartment(@RequestBody Department department, 
                                            @RequestParam(required = false) Long createdBy) {
        try {
            Department created = departmentService.createDepartment(department, createdBy);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "部门创建成功");
            response.put("data", created);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 更新部门
    @PutMapping("/{id}")
    public ResponseEntity<?> updateDepartment(@PathVariable Long id, @RequestBody Department department) {
        try {
            Department updated = departmentService.updateDepartment(id, department);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "部门更新成功");
            response.put("data", updated);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 删除部门
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteDepartment(@PathVariable Long id) {
        try {
            departmentService.deleteDepartment(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "部门删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取部门详情
    @GetMapping("/{id}")
    public ResponseEntity<?> getDepartment(@PathVariable Long id) {
        try {
            Department department = departmentService.getDepartmentById(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", department);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取所有部门
    @GetMapping
    public ResponseEntity<?> getAllDepartments() {
        try {
            List<Department> departments = departmentService.getAllDepartments();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", departments);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取部门树结构
    @GetMapping("/tree")
    public ResponseEntity<?> getDepartmentTree() {
        try {
            List<Department> tree = departmentService.getDepartmentTree();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", tree);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取顶级部门
    @GetMapping("/top-level")
    public ResponseEntity<?> getTopLevelDepartments() {
        try {
            List<Department> departments = departmentService.getTopLevelDepartments();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", departments);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取子部门
    @GetMapping("/{parentId}/children")
    public ResponseEntity<?> getChildDepartments(@PathVariable Long parentId) {
        try {
            List<Department> departments = departmentService.getChildDepartments(parentId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", departments);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取部门管理员管理的部门
    @GetMapping("/manager/{managerId}")
    public ResponseEntity<?> getDepartmentsByManager(@PathVariable Long managerId) {
        try {
            List<Department> departments = departmentService.getDepartmentsByManager(managerId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", departments);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 设置部门管理员
    @PutMapping("/{id}/manager")
    public ResponseEntity<?> setDepartmentManager(@PathVariable Long id, 
                                                @RequestParam(required = false) Long managerId) {
        try {
            Department department = departmentService.setDepartmentManager(id, managerId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", managerId != null ? "部门管理员设置成功" : "部门管理员已清除");
            response.put("data", department);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 检查用户是否有部门管理权限
    @GetMapping("/permission")
    public ResponseEntity<?> checkDepartmentPermission(@RequestParam Long userId, 
                                                     @RequestParam Long departmentId) {
        try {
            boolean hasPermission = departmentService.hasDepartmentPermission(userId, departmentId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("hasPermission", hasPermission);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取用户可管理的部门
    @GetMapping("/user/{userId}/manageable")
    public ResponseEntity<?> getUserManageableDepartments(@PathVariable Long userId) {
        try {
            List<Department> departments = departmentService.getUserManageableDepartments(userId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", departments);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 验证部门名称是否唯一
    @GetMapping("/validate-name")
    public ResponseEntity<?> validateDepartmentName(@RequestParam String name, 
                                                  @RequestParam(required = false) Long excludeId) {
        try {
            boolean isUnique = departmentService.isDepartmentNameUnique(name, excludeId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("isUnique", isUnique);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 